package leetcode_数组;

/**
 * 岛屿数量
 * <p>算法: 深度优先搜索</p>
 *
 * @author yezh
 * @date 2023/8/10 15:15
 */
public class _200 {

    public int numIslands(char[][] grid) {
        int ans = 0;
        for (int i = 0; i < grid.length; i++)
            for (int j = 0; j < grid[0].length; j++)
                if (grid[i][j] == '1') {
                    ++ans;
                    dfs(i, j, grid);
                }
        return ans;
    }

    void dfs(int i, int j, char[][] grid) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return;
        if (grid[i][j] != '1') return;
        grid[i][j] = '0';
        dfs(i - 1, j, grid);
        dfs(i + 1, j, grid);
        dfs(i, j - 1, grid);
        dfs(i, j + 1, grid);
    }

}
